<template>
  <div class="departments">
    <el-card>
      <template #header>
        <h3>组织结构</h3>
      </template>
      <div class="tree">
        <TreeItem :item="topInfo" />
        <hr>
        <el-tree :data="list" :props="{ children: 'children' }">
          <template v-slot="{ data }">
            <TreeItem :item="data" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <Dialog :init-list="initList" @getData="getData" />
  </div>
</template>
<script>
import TreeItem from './components/tree-item.vue'
import Dialog from './components/dialog.vue'
import { companyDepartment } from '@/api/departments.js'
export default {
  name: '',
  components: { TreeItem, Dialog },
  data() {
    return {
      initList: [],
      topInfo: {
        name: '传智播客',
        manager: '负责人',
        isTop: true,
        id: ''
      },
      list: []
    }
  },
  created() {
    this.getData()
  },

  methods: {
    async getData() {
      // 获取所有部门
      const res = await companyDepartment()
      console.log(res)
      // 保存初始数据
      this.initList = res.data.depts
      this.list = this.changeData(res.data.depts, '')
    },
    // 将数组转换成树形结构
    changeData(arr, str = '') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.departments {
  padding-top: 30px;
  .el-card {
    width: 90%;
    margin: 0 auto;
    .tree {
      padding: 0 80px;
    }
  }
}
</style>
